package com.test.multithread.deadlock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class DeadLock{
    static Object o1 = new Object();
    static Object o2 = new Object();

    /*
    互斥条件：一个资源每次只能被一个线程使用；
    请求与保持条件：一个线程因请求资源而阻塞时，对已获得的资源保持不放；
    不剥夺条件：进程已经获得的资源，在未使用完之前，不能强行剥夺；
    循环等待条件：若干线程之间形成一种头尾相接的循环等待资源关系。*/
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                synchronized (o1) {
                    System.out.println("线程1锁o1");
                    try {
                        Thread.sleep(1);//让当前线程睡眠，保证让另一线程得到o2，防止这个线程启动一下连续获得o1和o2两个对象的锁。
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (o2) {
                        System.out.println("线程1锁o2");
                    }
                }
            }
        });
        t1.setDaemon(true);
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                synchronized (o2) {
                    System.out.println("线程2锁o2");
                    synchronized (o1) {
                        System.out.println("线程2锁o1");
                    }
                }
            }
        });
        t2.start();

        boolean isKeepOn = true;
        while (true) {
            ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
            long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
            if (deadlockedThreads != null) {

                System.out.println("检测到死锁");
                ThreadInfo[] infos = threadMXBean.getThreadInfo(deadlockedThreads, true, true);
                for (ThreadInfo info : infos) {
                    System.out.println("死锁线程: " + info.getThreadName());
                    System.out.println("堆栈跟踪:");
                    for (StackTraceElement element : info.getStackTrace()) {
                        System.out.println("    at " + element.toString());
                    }
                }
                isKeepOn = false;
                return;
            } else {
                System.out.println("未检测到死锁");
            }
        }

    }
}
